<template>
    <div class="card flex_col flex_start_self m5 p10">
        <label class="flex_center_self">OTA</label>
        <div class="flex_row_center mt5">
            <label>{{ ctx.path }}</label>
        </div>
        <div class="flex_row_center mt5">
            <el-button type="primary" class="ml5" @click="onClickOpen">打开</el-button>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { open } from '@tauri-apps/plugin-dialog';
import { readFile } from '@tauri-apps/plugin-fs';
import { reactive } from 'vue';
import { runAction } from '../utils/ui';
import service, { CMD_OTA_COMPLETE, CMD_OTA_START, CMD_OTA_TRANSLATE } from '../service/service';
import { Md5 } from 'ts-md5';

interface Ctx {
    path: string,
}

const ctx = reactive<Ctx>({
    path: ''
})

async function onClickOpen() {
    const file = await open({
        multiple: false,
        directory: false,
        filters: [{
            name: '固件',
            extensions: ['bin'],
        }]
    });
    if (file == null) {
        return;
    }
    ctx.path = file;
    const buf = await readFile(file);

    runAction('OTA', '固件更新', async (dialog) => {
        const length = buf.length;
        dialog.setMsg('start');
        await service.simpleReq(CMD_OTA_START, length);

        let id = 0;
        let index = 0;
        while (index < length) {
            let n = length - index;
            if (n > 240) {
                n = 240;
            }
            let pkg = buf.slice(index, index + n);
            let data = [id, pkg];
            await service.simpleReq(CMD_OTA_TRANSLATE, data);
            id += 1;
            index += n;
            dialog.setMsg(`translate:${ (index * 100 / length).toFixed(2) }%`);
        }

        const md5 = new Md5();
        const m = md5.appendByteArray(buf)
        .end(true) as Int32Array;
        const pkg = new Uint8Array(m.buffer);
        dialog.setMsg('complete');

        await service.simpleReq(CMD_OTA_COMPLETE, pkg);
    });
}








</script>
